package com.chain.BrotherExchange.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.support.design.widget.TabLayout;
import android.support.v7.widget.AppCompatImageView;
import android.support.v7.widget.RecyclerView;
import android.widget.Button;
import android.widget.TextView;

import com.chain.BrotherExchange.C;
import com.chain.BrotherExchange.R;
import com.chain.BrotherExchange.data.Resource;
import com.chain.BrotherExchange.data.model.MarketPair;
import com.chain.BrotherExchange.event.VisualQuotationEvent;
import com.chain.BrotherExchange.ui.adapter.VisualQuotationAdapter;
import com.chain.BrotherExchange.ui.core.BaseActivity;
import com.chain.BrotherExchange.ui.listener.LoginInterceptListener;
import com.chain.BrotherExchange.viewmodel.QuotationViewModel;
import com.chain.BrotherExchange.viewmodel.core.ViewModelProviders;
import com.chain.BrotherExchange.widget.kline.KLineView;
import com.example.common.widget.state.NetworkStateLayout;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;

import butterknife.Bind;

/**
 * 可视化行情
 */
public class VisualQuotationActivity extends BaseActivity {

    @Bind(R.id.title_text)
    TextView titleText;
    @Bind(R.id.kline_view)
    KLineView mKLineView;
    @Bind(R.id.tab_layout)
    TabLayout mTabLayout;
    @Bind(R.id.arrow_back_image)
    AppCompatImageView arrowBackImage;
    @Bind(R.id.network_state_layout)
    NetworkStateLayout mNetworkStateLayout;
    @Bind(R.id.price_text)
    TextView priceText;
    @Bind(R.id.price_info_text)
    TextView priceInfoText;
    @Bind(R.id.max_number_text)
    TextView maxNumberText;
    @Bind(R.id.min_number_text)
    TextView minNumberText;
    @Bind(R.id.hour_number_text)
    TextView hourNumberText;
    @Bind(R.id.scope_text_view)
    TextView mScopeTextView;
    @Bind(R.id.buy_type_button)
    Button mBuyTypeButton;
    @Bind(R.id.sale_type_button)
    Button mSaleTypeButton;
    @Bind(R.id.recycler_view)
    RecyclerView mRecyclerView;
    @Bind(R.id.buy_number_text)
    TextView mBuyNumberText;
    @Bind(R.id.sale_number_text)
    TextView mSaleNumberText;
    @Bind(R.id.order_price_text)
    TextView mOrderNumberText;
    @Bind(R.id.record_network_state_layout)
    NetworkStateLayout mRecordNetworkStateLayout;

    private String mSymbol;
    private QuotationViewModel mViewModel;
    private VisualQuotationAdapter mAdapter;

    public static void launch(Context context, String tokenName) {
        context.startActivity(new Intent(context, VisualQuotationActivity.class)
                .putExtra(C.EXTRA_TOKEN_SYMBOL, tokenName));
    }

    @Override
    protected int getLayoutID() {
        return R.layout.activity_visual_quotation;
    }

    @Override
    protected void initActions() {
        // title
        mSymbol = getIntent().getStringExtra(C.EXTRA_TOKEN_SYMBOL);
        titleText.setText(mSymbol);
        arrowBackImage.setOnClickListener(v -> onBackPressed());

        if (mSymbol != null) {
            mBuyNumberText.setText(getString(R.string.number) + "(" + mSymbol.split("/")[0] + ")");
            mSaleNumberText.setText(mBuyNumberText.getText().toString());
            mOrderNumberText.setText(getString(R.string.price) + "(" + mSymbol.split("/")[1] + ")");
        }

        // 数据
        mViewModel = ViewModelProviders.of(this).get(QuotationViewModel.class);

        // 买卖盘
        mRecyclerView.setNestedScrollingEnabled(false);
        mAdapter = new VisualQuotationAdapter();
        mRecyclerView.setAdapter(mAdapter);

        // 初始化买买
        initRecord();
        mRecordNetworkStateLayout.setOnAnewRequestNetworkListener(this::initRecord);

        // 初始化交易对数据
        initMarketPairData();

        // 切换时间
        initSwitchResolution();

        // 初始化K线数据
        initVisualQuotationData();
    }

    private void initRecord() {
        mViewModel.record(mSymbol, result ->
                Resource.load(this, result, mRecordNetworkStateLayout, recordList ->
                        mAdapter.setData(recordList))
        );
    }

    private void initMarketPairData() {
        mViewModel.marketPair(mSymbol, result -> {
            MarketPair.DataBean.ListBean list = result.getData().getList();
            priceInfoText.setText("≈" + list.getCny_price() + "CNY");
            maxNumberText.setText(list.getHigh());
            minNumberText.setText(list.getLow());
            hourNumberText.setText(list.getAmount());
            priceText.setText(list.getPrice());
            mScopeTextView.setText(list.getScope() + "%");

            if (list.getScope().contains("-")) {
                priceText.setTextColor(getResources().getColor(R.color.colorRosePlate));
                mScopeTextView.setTextColor(getResources().getColor(R.color.colorRosePlate));
            } else {
                priceText.setTextColor(getResources().getColor(R.color.colorDrop));
                mScopeTextView.setTextColor(getResources().getColor(R.color.colorDrop));
            }

            // 买入
            mBuyTypeButton.setOnClickListener(new LoginInterceptListener(v -> {
                MainActivity.launchToCoin(this);
                EventBus.getDefault().postSticky(new VisualQuotationEvent(C.API_ENTRUST_BUY, list));
            }));

            // 卖出
            mSaleTypeButton.setOnClickListener(new LoginInterceptListener(v -> {
                MainActivity.launchToCoin(this);
                EventBus.getDefault().postSticky(new VisualQuotationEvent(C.API_ENTRUST_SELL, list));
            }));
        });
    }

    private void initSwitchResolution() {
        mTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                String tabString = tab.getText().toString();
                if (tabString.equals(getString(R.string.marks_15))) {
                    mViewModel.minutesKLine();
                } else if (tabString.equals(getString(R.string.hours_1))) {
                    mViewModel.anHourKLine();
                } else if (tabString.equals(getString(R.string.hours_4))) {
                    mViewModel.fourHoursKLine();
                } else if (tabString.equals(getString(R.string.day_1))) {
                    mViewModel.oneDayKLine();
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    private void initVisualQuotationData() {
        mViewModel.kLine(mSymbol, resource -> {
            Resource.load(this, resource, mNetworkStateLayout, result -> {
                mKLineView.resetDataList(new ArrayList<>(result));
                mKLineView.setCrossHairMoveMode(KLineView.CROSS_HAIR_MOVE_OPEN);
            });
        });

        // 加载新数据
        mKLineView.setOnRequestDataListListener(() -> {

        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mViewModel.clearTimer();
    }
}
